<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wh\model\StockType as StockTypeModel;
use think\Db;

/**
 * 物流类型控制器
 * @package app\admin\controller
 */
class StockType extends Admin
{

    //最多联动几级，封顶3级
    public $curr_level = 1;
    /**
     * 首页
     * @return mixed
     * @throws \Exception
     */
    public function index()
    {
        // 保存模块排序
        if ($this->request->isPost()) {
            $modules = $this->request->post('sort/a');
            if ($modules) {
                $data = [];
                foreach ($modules as $key => $module) {
                    $data[] = [
                        'id'   => $module,
                        'sort' => $key + 1
                    ];
                }
                $MenuModel = new StockTypeModel();
                if (false !== $MenuModel->saveAll($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }

        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 配置分组信息
        $i = 0;
        $pid = input('pid',0);
        $tab_list = [];
        $list_group = StockTypeModel::getGroup();
        foreach ($list_group as $key => $value) {
            if($i == 0 && $pid == 0)$pid = $key;

            $tab_list[$key]['title'] = $value;
            $tab_list[$key]['url']  = url('index', ['pid' => $key]);

            $i++;
        }
        $max_level = 0;
        $group = input('group');
        if(!empty($group)){
            $pid = 0;
            $max_level = 1;
        }

        // 获取节点数据
        $data_list = StockTypeModel::getMenusByGroup($pid);

        $max_level = $this->request->get('max', $max_level);

        $this->assign('pid', $pid);
        $this->assign('menus', $this->getNestMenu($data_list, $max_level,$pid));

        $this->assign('tab_nav', ['tab_list' => $tab_list, 'curr_tab' => $pid]);
        $this->assign('page_title', '');
        return $this->fetch();
    }

    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    private function getNestMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable  = $value['status'] == 0 ? 'dd-disable' : '';

                // 组合节点
                $result .= '<li class="dd-item dd3-item '.$disable.'" data-id="'.$value['id'].'" data-pid="'.$value['pid'].'">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content"> <i class=" fa fa-fw '.$value['icon'].'"></i>'.$value['title'];
                /*if ($value['url_value'] != '') {
                    $result .= '<span class="link"><i class="fa fa-link"></i> '.$value['url_value'].'</span>';
                }*/
                $result .= '<div class="action">';
                //新增子分类，最多四级
                if($curr_level < $this->curr_level)$result .= '<a class="pop" href="'.url('add', ['pid' => $value['pid'],'pid2' => $value['id']]).'?_pop=1" data-toggle="tooltip" data-original-title="新增子分类" data-layer="{&quot;area&quot;:[&quot;780px&quot;,&quot;85%&quot;],&quot;title&quot;:[&quot;新增子分类&quot;,&quot;font-size:24px;text-align: center;&quot;]}"><i class="list-icon fa fa-plus fa-fw"></i></a>';
                //编辑
                $result .= '<a class="pop" href="'.url('edit', ['id' => $value['id']]).'?_pop=1" data-toggle="tooltip" data-original-title="编辑" data-layer="{&quot;area&quot;:[&quot;780px&quot;,&quot;85%&quot;],&quot;title&quot;:[&quot;编辑&quot;,&quot;font-size:24px;text-align: center;&quot;]}"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                if ($value['status'] == 0) {
                    // 启用
                    $result .= '<a href="javascript:void(0);" data-ids="'.$value['id'].'" class="enable" data-toggle="tooltip" data-original-title="启用"><i class="list-icon fa fa-check-circle-o fa-fw"></i></a>';
                } else {
                    // 禁用
                    $result .= '<a href="javascript:void(0);" data-ids="'.$value['id'].'" class="disable" data-toggle="tooltip" data-original-title="禁用"><i class="list-icon fa fa-ban fa-fw"></i></a>';
                }
                $result .= '<a href="'.url('delete', ['ids' => $value['id']]).'" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                $result .= '</div>';

                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    $level_list = StockTypeModel::getMenusByGroup($value['id']);
                    // 下级节点
                    $children = $this->getNestMenu($level_list, $max_level, $value['id'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">'.$children.'</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }

    /**
     * 新增
     * @param int $pid 所属父id
     * @return mixed
     * @throws \Exception
     */
    public function add($pid = 0)
    {
        $id = input('param.id');
        // 获取数据
        $info = Db::name('wh_stock_type')->where(['id'=>$id])->find();

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            if(empty($data['link_type_id']))$data['link_type_id'] = '';

            // 验证失败 输出错误信息
            if(empty($data['title'])) $this->error('名称不能为空');

            if(!empty($id))$re = Db::name('wh_stock_type')->where(['id'=>$id])->update($data);
            else $re = $id = Db::name('wh_stock_type')->insertGetId($data);

            //同步关联物料类型
            if(!empty($data['link_type_id']))Db::name('wh_stock_type')->where(['id'=>$data['link_type_id']])->update(['link_type_id'=>$id]);

            if(!empty($re))$this->success('操作成功','','_parent_reload');
            else $this->error('操作失败');
        }

        $icon = '';
        $color = '';
        $icon_hidden = 'hidden';
        $pid2 = input('pid2');//三级分类
        if(!empty($info))$pid = Db::name('wh_stock_type')->where(['id'=>$info['pid']])->value('pid');
        if(!empty($pid2)){
            $p_list = StockTypeModel::getGroup($pid);
            $pid = $pid2;
        }
        else{
            //$p_list = StockTypeModel::getGroup($pid);
            $p_list = StockTypeModel::getGroup(0);
        }
        if(empty($pid)){
            $icon = 'fa fa-ils';
            $icon_hidden = '';
        }
        if(empty($info))$info['pid'] = $pid2;
        //判断是否是最后一级分类，同步物料类型，仅最后一级分类可用
        $level = StockTypeModel::getLevle($info['pid']);

        $css = <<<EOF
           <style>
                .js-icon-list li {
                    width: inherit;
                    padding: 10px;
                }
           </style>
EOF;
        $formItems = [
            ['select:12', 'pid', '所属类型', '所属上级类型', $p_list, $pid],
            ['text:12||||must', 'title', '类型名称'],
            ['text:12', 'code', '编码'],
            ['icon:12||||must', 'icon', '图标','',$icon,'',$icon_hidden],
            ['colorpicker:12||||must', 'color', '颜色','',$color,'','',$icon_hidden],
            ['text:12', 'sort', '排序', '', 100],
        ];
        //如果是最后一级分类，同步物料类型，仅最后一级分类可用
        if($level == $this->curr_level)$formItems[] = ['linkages:12', 'link_type_id', '同步物料类型', '绑定物料类型，可同步新增该库存信息', 'wh_stock_type', $this->curr_level+1,'','id,title,pid'];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增类型')
            ->addFormItems($formItems)
            ->setFormData($info)
            ->setExtraCss($css)
            //->layout(['pid'=>12,'title'=>12,'sort'=>12,'icon'=>12,'color'=>12,])
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id id
     * @return mixed
     */
    public function edit($id=null)
    {

        return $this->add();
        $id = input('param.id');
        // 获取数据
        $info = StockTypeModel::find($id);

        if ($this->request->isPost()) {
            $data = $this->request->post();
            // 验证失败 输出错误信息
            if(empty($data['title'])) $this->error('名称不能为空');

            // 更新数据
            if (StockTypeModel::update($data)) {
                $this->success('编辑成功','','_parent_reload');
            } else {
                $this->error('编辑失败');
            }
        }

        $icon = '';
        $color = '';
        $icon_hidden = 'hidden';
        $pid = Db::name('wh_stock_type')->where(['id'=>$info['pid']])->value('pid');
        if(empty($pid)){
            $icon_hidden = '';
        }
        $p_list = StockTypeModel::getGroup($pid);

        $css = <<<EOF
           <style>
                .js-icon-list li {
                    width: inherit;
                    padding: 10px;
                }
           </style>
EOF;
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增类型')
            ->addHidden('id')
            ->addFormItems([
                ['select:12', 'pid', '所属类型', '所属上级类型', $p_list, $info['pid']],
                ['text:12||||must', 'title', '类型名称'],
                ['text:12', 'code', '编码'],
                ['icon:12||||must', 'icon', '图标','',$icon,'',$icon_hidden],
                ['colorpicker:12||||must', 'color', '颜色','',$color,'','',$icon_hidden],
                ['text:12', 'sort', '排序', '', 100],
                ['linkages:12', 'link_type_id', '同步物料类型', '绑定物料类型，可同步新增该库存信息', 'wh_stock_type', 4,'','id,title,pid'],
            ])
            ->setFormData($info)
            ->setExtraCss($css)
            //->layout(['pid'=>12,'title'=>12,'sort'=>12,'icon'=>12,'color'=>12,])
            ->fetch();
    }

    /**
     * 保存排序
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!empty($data)) {
                $menus = $this->parseMenu($data['menus']);
                foreach ($menus as $menu) {
                    if ($menu['pid'] == 0) {
                        unset($menu['pid']);
                        //continue;
                    }
                    StockTypeModel::update($menu);
                }
                $this->success('保存成功');
            } else {
                $this->error('没有需要保存的类型');
            }
        }
        $this->error('非法请求');
    }

    /**
     * 递归解析
     * @param array $menus 多维数组
     * @param int $pid 上级id
     * @return array 解析成可以写入数据库的格式
     */
    private function parseMenu($menus = [], $pid = 0)
    {
        $sort   = 1;
        $result = [];
        foreach ($menus as $menu) {
            $result[] = [
                'id'   => (int)$menu['id'],
                'pid'  => (int)$pid,
                'sort' => $sort,
            ];
            if (isset($menu['children'])) {
                $result = array_merge($result, $this->parseMenu($menu['children'], $menu['id']));
            }
            $sort ++;
        }
        return $result;
    }

    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;
        if(!empty($record['pids']))$ids = $record['pids'];
        $pids = [];

        foreach ($ids as $id) {

            switch ($type) {
                case 'enable':
                    if (false === StockTypeModel::where('id', $id)->setField('status', 1)) {
                        $this->error('启用失败，分类ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === StockTypeModel::where('id', $id)->setField('status', 0)) {
                        $this->error('禁用失败，分类ID：'.$id);
                    }
                    break;
                case 'delete':

                    StockTypeModel::where('id', 'in', $id)->delete();
                    //递归删除子ID
                    $pid = Db::name('wh_stock_type')->where(['pid'=>$id])->column('id','id');
                    $pids = array_merge($pids,$pid);
                    break;
                default:
                    $this->error('非法操作');
            }

            action_log('role_'.$type, 'wh', $id, UID);
        }
        if(!empty($pids)){
            $record['pids']=$pids;
            $this->setStatus($type,$record);
        }

        $this->success('操作成功');
    }
}
